package com.zzc.legou.auth.config;

import com.zzc.legou.auth.config.properties.JwtCAProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.sql.DataSource;
import java.security.KeyPair;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    public PasswordEncoder passwordEncoder;

    //密钥
    @Autowired
    private JwtCAProperties jwtCAProperties;

    /**
     * 安全性约束
     * 通过security对象来定义OAuth2服务器的访问规则 指定只有经过身份认证的用户才能访问OAuth2服务器
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                // 开启/oauth/token_key验证端口无权限访问
                .tokenKeyAccess("permitAll()")
                // 开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess("isAuthenticated()");
    }

    /**
     * 存储方式的设置
     * 定义Ouath2客户端的ID 密钥、授权类型、作用域等信息
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 配置授权服务器存储第三方客户端的信息 基于DB存储 oauth_client_details
        clients.withClientDetails(clientDetails());
       /* clients.inMemory()
                //客户端认证
                .withClient(AuthorizationConstant.Auth_TYPE_CLIENTID)
                //加盐
                .secret(passwordEncoder.encode("123456"))
                //授予权限的类型
                .authorizedGrantTypes(AuthorizationConstant.CLIENT_CREDENTIALS, AuthorizationConstant.REFRESH_TOKEN)
                // 作用的范围
                .scopes(AuthorizationConstant.SCOPE_SELECT)
                //授权者
                .authorities(AuthorizationConstant.OAUTH2)
                //密码认证
                .and()
                .withClient(AuthorizationConstant.Auth_TYPE_PASSWORD)
                //加盐
                .secret(passwordEncoder.encode("123456"))
                //授予权限的类型
                .authorizedGrantTypes(AuthorizationConstant.CLIENT_CREDENTIALS, AuthorizationConstant.REFRESH_TOKEN)
                // 作用的范围
                .scopes(AuthorizationConstant.SCOPE_SERVER)
                //授权者
                .authorities(AuthorizationConstant.OAUTH2);*/
    }

    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 配置Oauth2服务器的端点信息
     * 这个方法来定义身份认证管理器、用户详细信息服务、令牌存储等信息
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager);
        // 配置tokenServices参数
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(endpoints.getTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
        tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
        tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30)); // 30天
        endpoints.tokenServices(tokenServices);
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        //jwt密钥设置
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        return converter;
    }

    //jwt密钥设置
    @Bean
    public KeyPair keyPair() {
        //证书的名称  证书的私钥
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(new ClassPathResource(jwtCAProperties.getKeyPairName()), jwtCAProperties.getKeyPairSecret().toCharArray());
        //获取证书别名
        return keyFactory.getKeyPair(jwtCAProperties.getKeyPairAlias(), jwtCAProperties.getKeyPairStoreSecret().toCharArray());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
}
